package bucket

import (
	"clouds.lgb24kcs.cn/controllers/bucket/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/oss"
	"errors"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type BucketList struct {
}

var BucketListApi BucketList

func (b BucketList) List(c *gin.Context, req request.ListBucketReq, userId int64) {
	api := oss.OSS{}
	/*用当前登录用户id查询数据库，获取当前用户所有的bucket信息*/
	buckets := []models.Storage{}
	var Count int64
	tx := global.APP.DB.Where("userid=?", userId).Find(&buckets).Count(&Count)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.BucketList, tx.Error.Error())
	} else if tx.RowsAffected == 0 {

		utils.Fail(c, errorx.BucketList, errors.New("没有数据").Error())
	} else {
		// 检查bucket是否存在oss存储中、
		list := []map[string]interface{}{}
		for _, item := range buckets {
			sve := api.NewClient(item.Accesskey, item.Secretkey, item.Zone)
			if err := api.BucketExists(sve, item.Bucketname); err == nil {
				list = append(list, map[string]interface{}{
					"Id":          int64(item.ID),
					"user_id":     item.Userid,
					"alias":       item.Alias,
					"bucket_name": item.Bucketname,
					"create_at":   item.CreatedAt.Format(time.DateTime),
				})
			} else {

			}
			//else {
			//	list = append(list, map[string]interface{}{
			//		"Id":          int64(item.ID),
			//		"user_id":     item.Userid,
			//		"alias":       item.Alias,
			//		"bucket_name": item.Bucketname,
			//		"create_at":   item.CreatedAt.Format(time.DateTime),
			//	})
			//}
		}
		count := strconv.Itoa(int(Count))
		//if err := history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
		//	utils.Fail(c, errorx.ObjectSearch, err.Error())
		//} else {
		//
		//}
		utils.Success(c, 0, map[string]interface{}{
			"count": count,
			"list":  list,
		})
	}

}
